<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   @click="handleDelete">删 除
                   <!-- v-if="permission.trainplan_delete" -->
        </el-button>
        <el-button type="warning"
                   size="small"
                   plain
                   icon="el-icon-download"
                   @click="handleExport">导出
                   <!-- v-if="permission.prod_unit_export" -->
        </el-button>
      </template>
      <!-- 培训开始时间表格自定义 -->
      <template slot="trainTimeStart" slot-scope="scope">
        <span>{{formatDate(scope.row.trainTimeStart)}}</span>
      </template>
      <template slot="tartinTimeEnd" slot-scope="scope">
        <span>{{formatDate(scope.row.tartinTimeEnd)}}</span>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/jypx/edutrainplan/trainplan";
  import {mapGetters} from "vuex";
  import { getToken } from "@/util/auth";
  import moment from 'moment'

  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          labelWidth: 110,
          searchLabelWidth: 110,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "培训计划名称",
              prop: "pxjhmc",
              align: "center",
              search: true,
              span: 24,
              rules: [{
                required: true,
                message: "请输入培训计划名称",
                trigger: "blur"
              }]
            },
            {
              label: "培训开始日期",
              prop: "trainTimeStart",
              align: "center",
              type: 'datetime',
              width: 160,
              rules: [{
                required: true,
                message: "请选择培训日期",
                trigger: "blur"
              }],
              slot: true
            },
            {
              label: "培训结束日期",
              prop: "tartinTimeEnd",
              align: "center",
              type: 'datetime',
              width: 160,
              rules: [{
                required: true,
                message: "请选择培训日期",
                trigger: "blur"
              }],
              slot: true
            },
            {
              label: "培训课程",
              prop: "courseId",
              align: "center",
              type: "select",
              span: 24,
              dicUrl: "/api/eduCourse/course/getCourseKcmc",
              props: {
                label: "kcmc",
                value: "id",
              },
              rules: [{
                required: true,
                message: "请选择培训课程",
                trigger: "blur"
              }]
            },
            {
              label: "培训人员",
              prop: "pxryId",
              align: "center",
              type: "select",
              span: 24,
              dicUrl: "/api/emerDrill/drill/getPersonInfo",
              props: {
                label: "name",
                value: "id",
              },
              rules: [{
                required: true,
                message: "请选择培训人员",
                trigger: "blur"
              }]
            },
            {
              label: "培训学时",
              prop: "pxxs",
              align: "center",
              rules: [{
                // required: true,
                pattern: /^(([1-9]{1}\d*)|(0{1}))?$/,
                message: "请输入数字",
                trigger: "blur"
              }]
            },
            {
              label: "培训类别",
              prop: "pxlb",
              align: "center",
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=pxlb",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
              rules: [{
                required: true,
                message: "请选择培训类别",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              prop: "bz",
              type: "textarea",
              maxRows:4,
              minRows:2,
              span: 24,
              hide: true
              // rules: [{
              //   required: true,
              //   message: "请输入备注",
              //   trigger: "blur"
              // }]
            },
            {
              label: "制定日期",
              prop: "createTime",
              align: "center",
              valueFormat: 'yyyy-MM-dd HH:mm:ss',
              display: false
            }
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          // addBtn: this.vaildData(this.permission.trainplan_add, false),
          // viewBtn: this.vaildData(this.permission.trainplan_view, false),
          // delBtn: this.vaildData(this.permission.trainplan_delete, false),
          // editBtn: this.vaildData(this.permission.trainplan_edit, false)
        };
      },
      ids() {
        let ids = [];
             this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      formatDate(val) {
        if (!val || val.length == 0) {
          return "";
        } else {
          return moment(val).format('YYYY-MM-DD HH:mm:ss');
        }
      },

      handleExport() {
        this.$confirm("是否导出?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          let pxjhmc = this.query.pxjhmc !== undefined && this.query.pxjhmc !== "" && this.query.pxjhmc !== null ? this.query.pxjhmc : "";
          window.open(`/api/eduTrainPlan/trainplan/exportTrainPlan?${this.website.tokenHeader}=${getToken()}&pxjhmc=${pxjhmc}`);
        });
      },
      rowSave(row, done, loading) {
        if (new Date(row.trainTimeStart).getTime() >= new Date(row.tartinTimeEnd).getTime()) {
					this.$message.warning('培训开始日期不能晚于或等于结束日期！');
          loading();
					return
				}
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        if (new Date(row.trainTimeStart).getTime() >= new Date(row.tartinTimeEnd).getTime()) {
					this.$message.warning('培训开始日期不能晚于或等于结束日期！');
          loading();
					return
				}
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        if (type == "add") {
          this.form = {pxxs: 1};
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
/* .el-form-item__label{
  width: 110px !important;
}
.el-form-item__content {
  margin-left: 110px !important;
} */
</style>
